package jjn.round1;

import commons.TreeNode;

/**
 * @author Jjn
 * @since 2022/8/23 23:03
 */
public class LeetCode55_BalancedTree {

    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftDepth = queryDepth(root.left);
        int rightDepth = queryDepth(root.right);
        if (Math.abs(leftDepth - rightDepth) > 1) {
            return false;
        }
        return isBalanced(root.left) && isBalanced(root.right);
    }

    private int queryDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = queryDepth(root.left) + 1;
        int right = queryDepth(root.right) + 1;
        return Math.max(left, right);
    }
}
